package followme.yaohuile.com.followme.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import followme.yaohuile.com.followme.adapter.recommend.RecommendDingyueGridViewAdapter;
import followme.yaohuile.com.followme.adapter.recommend.RecommendListViewAdapter;
import followme.yaohuile.com.followme.adapter.recommend.RecommendViewPagerAdapter;
import followme.yaohuile.com.followme.bean.recommend.FourBean;
import followme.yaohuile.com.followme.bean.recommend.ListData;
import followme.yaohuile.com.followme.bean.recommend.ListViewData;
import followme.yaohuile.com.followme.bean.recommend.Recommend;
import followme.yaohuile.com.followme.bean.recommend.Slide;
import followme.yaohuile.com.followme.customview.RecommendGridView;
import followme.yaohuile.com.followme.customview.RefreshLayout;

import followme.yaohuile.com.followme.R;
import followme.yaohuile.com.followme.network.recommend.NetWork;
import followme.yaohuile.com.followme.parsejson.recommend.ParserRecommend;
import followme.yaohuile.com.followme.parsejson.recommend.ParserRecommendListView;
import followme.yaohuile.com.followme.utils.recommend.UrlContants;

public class RecommendFragment extends Fragment implements RefreshLayout.OnLoadListener ,SwipeRefreshLayout.OnRefreshListener{

	private View view;
	private ViewPager viewPager;
    private ImageView categoryIv;
    private ImageView saleIv;
    private ImageView hotelIv;
    private ImageView planIv;
    private List<ImageView> list;
    private List<String> slideUrl;
    private Recommend recommend;
    private ListData listData;
    //记录上一个位置
    private int oldPosition;
    //记录当前位置
    private int currentPosition;
    private ScheduledExecutorService scheduledExecutorService;
    int page = 1;
    //热门推荐
    private String TRIP = "http://open.qyer.com/qyer/recommands/trip?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=357139052825648&track_app_version=6.8.2&track_app_channel=wandoujia&track_device_info=Droid4X&track_os=Android4.2.2&app_installtime=1447395547238&lat=40.049299&lon=116.296476&type=index&page=";

    private String triplast = "&count=10";

    private String tripUrl = TRIP + page + triplast;
    //小圆点
    private ImageView[] images;
    private List<String> viewPagerImgUrl = new ArrayList();

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 0x123:
                    recommend = (Recommend) msg.obj;
                    List<Slide> slide = recommend.getData().getSlide();
                    BitmapUtils bitmapUtils = new BitmapUtils(getActivity());
                    for (int i = 0; i < slide.size(); i++) {
                        ImageView imageView = new ImageView(getActivity());
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        bitmapUtils.display(imageView, slide.get(i).getPhoto());
                        list.add(imageView);
                        viewPagerImgUrl.add(slide.get(i).getUrl());
                    }
                    adapter = new RecommendViewPagerAdapter(list, viewPagerImgUrl, getActivity());
                    if (adapter != null) {
                        viewPager.setAdapter(adapter);
                    }
                    images = new ImageView[slide.size()];
                    for (int i = 0; i < images.length; i++) {
                        images[i] = new ImageView(getActivity());
                        images[i].setImageResource(R.mipmap.icon01);
                        images[i].setMaxHeight(20);
                        images[i].setAdjustViewBounds(true);
                        images[i].setTag(i);
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(12, 12);
                        params.setMargins(12, 0, 12, 0);
                        images[i].setLayoutParams(params);
                        images[i].setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                viewPager.setCurrentItem((Integer) v.getTag());
                            }
                        });
                        llDot.addView(images[i]);
                    }
                    images[0].setImageResource(R.mipmap.icon02);
                    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        }

                        @Override
                        public void onPageSelected(int position) {
                            for (int i = 0; i < images.length; i++) {
                                images[i].setImageResource(R.mipmap.icon01);
                            }
                            images[position].setImageResource(R.mipmap.icon02);
                            oldPosition = position;
                            currentPosition = position;
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                    listView.addHeaderView(viewHeader);
                    bitmapUtils.display(findnextiv1, recommend.getData().getSubject().get(0).getPhoto());
                    bitmapUtils.display(findnextiv2, recommend.getData().getSubject().get(1).getPhoto());
                    bitmapUtils.display(findnextiv3, recommend.getData().getSubject().get(2).getPhoto());
                    listView.addHeaderView(view1);
                    bitmapUtils.display(dingyueiv1, recommend.getData().getDiscount_subject().get(0).getPhoto());
                    RecommendDingyueGridViewAdapter recommendDingyueGridViewAdapter = new RecommendDingyueGridViewAdapter(recommend.getData().getDiscount(), getActivity());
                    gridView.setAdapter(recommendDingyueGridViewAdapter);

                    listView.addHeaderView(view2);
                    listView.addHeaderView(view3);
                    break;
                case 0x124:
                    listData = (ListData) msg.obj;
                    initListView();
                    if (listData != null) {
                        refreshLayout.setRefreshing(false);
                    }
                    break;
            }

        }
    };


    private RecommendViewPagerAdapter adapter;
    private LinearLayout llDot;
    private ListView listView;
    private View viewHeader;
    private ImageView findnextiv1;
    private ImageView findnextiv2;
    private ImageView findnextiv3;
    private View view1;
    private TextView dingyue;
    private ImageView dingyueiv1;
    private ImageView dingyueiv2;
    private TextView dingyuetv2;
    private RecommendGridView gridView;
    private TextView dingyueCheckAll;
    private View view2;
    private TextView textView;
    private View view3;
    private RefreshLayout refreshLayout;
    private List<ListViewData> listListViewData = new ArrayList();
    private RecommendListViewAdapter listViewAdapter;
    private ImageView qiandao;
    int visit = 0;
    private FourBean fourBean;
    private Handler handlera = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case 2:
                    fourBean = (FourBean) msg.obj;
//                    Intent intent = new Intent(getActivity(), DiscountWeb.class);
//                    String urlq = fourBean.getQyer_url().toString();
//                    if (urlq != null) {
//                        intent.putExtra("url", urlq);
//                        startActivity(intent);
//                        break;
//                    }

            }
        }
    };
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_recommend, container,false);
        initView(view);
		viewHeader = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_recommend_viewpagerview, null);
        viewPager = (ViewPager) viewHeader.findViewById(R.id.fragment_recommmend_viewpager);
        qiandao = (ImageView) viewHeader.findViewById(R.id.qiandao);
        categoryIv = (ImageView) viewHeader.findViewById(R.id.category_iv);
        saleIv = (ImageView) viewHeader.findViewById(R.id.sale_iv);
        hotelIv = (ImageView) viewHeader.findViewById(R.id.hotel_iv);
        planIv = (ImageView) viewHeader.findViewById(R.id.plan_iv);
        llDot = (LinearLayout) viewHeader.findViewById(R.id.fragment_recommend_ll_dot);
        //锦囊监听
        categoryIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), CategoryActivity.class);
//                startActivity(intent);
            }
        });
        saleIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), DiscountActivity.class);
//                startActivity(intent);
            }
        });
        hotelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), HotelActivity.class);
//                startActivity(intent);
            }
        });
        planIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), TravelActivity.class);
//                startActivity(intent);
            }
        });
        //签到设置监听事件
        qiandao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), CheckInActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString("url", recommend.getData().getCheckin().getUrl());
//                intent.putExtras(bundle);
//                startActivity(intent);
            }
        });

        view1 = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_recommend_find, null);
        //TODO 发现下一站里面的查看更多 单击跳转到专题列表
        TextView checkAll = ((TextView) view1.findViewById(R.id.checkAll));
        checkAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), ZhanTiLieBiaoActivity.class);
//                startActivity(intent);
            }
        });
        findnextiv1 = (ImageView) view1.findViewById(R.id.findnextiv1);
        findnextiv2 = (ImageView) view1.findViewById(R.id.findnextiv2);
        findnextiv3 = (ImageView) view1.findViewById(R.id.findnextiv3);
        findnextiv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://appview.qyer.com/op/zt/20151102.html?source=app&client_id=qyer_android&track_user_id=&track_deviceid=357139058228813&track_app_version=6.8.2";
//                Intent intent = new Intent(getActivity(), FindNextWebActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString("url", url);
//                intent.putExtras(bundle);
//                startActivity(intent);
            }
        });
        findnextiv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://appview.qyer.com/op/zt/20151014.html?source=app&client_id=qyer_android&track_user_id=&track_deviceid=357139058228813&track_app_version=6.8.2";
//                Intent intent = new Intent(getActivity(), FindNextWebActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString("url", url);
//                intent.putExtras(bundle);
//                startActivity(intent);
            }
        });
        findnextiv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://appview.qyer.com/op/zt/20150918.html?source=app&client_id=qyer_android&track_user_id=&track_deviceid=357139058228813&track_app_version=6.8.2";
//                Intent intent = new Intent(getActivity(), FindNextWebActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString("url", url);
//                intent.putExtras(bundle);
//                startActivity(intent);
            }
        });
        view2 = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_recommend_discount, null);
        dingyue = (TextView) view2.findViewById(R.id.dingyue);
        dingyueiv1 = (ImageView) view2.findViewById(R.id.dingyueiv1);
        gridView = (RecommendGridView) view2.findViewById(R.id.dingyuegridview);
        dingyueCheckAll = (TextView) view2.findViewById(R.id.checkAll);
        ImageView dingyueiv1 = ((ImageView) view2.findViewById(R.id.dingyueiv1));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //// TODO: 15-11-19
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String idStr = recommend.getData().getDiscount().get(position).getId();
                parser100("http://open.qyer.com/lastminute/get_detail", "qyer_android", "9fcaae8aefc4f9ac4915", "1", "357139054098905",
                        "6.8.2", "lenovo", "Droid4X", "Android4.2.2", "1447399142426",
                        "40.049293", "116.296468", idStr, handlera);
            }
        });
        dingyueiv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //12月份
//                Intent intent = new Intent(getActivity(), DiscountWeb.class);
//                String urlq = recommend.getData().getDiscount_subject().get(0).getUrl();
//                intent.putExtra("url", urlq);
//                startActivity(intent);
            }
        });

        dingyueCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(),DiscountActivity.class);
//                startActivity(intent);
            }
        });
        TextView tv = ((TextView) view2.findViewById(R.id.checkAll));
        //TODO 跳转
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        view3 = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_recommend_textview, null);
        textView = (TextView) view3.findViewById(R.id.textview);
        initList();
        ParserRecommend.getData(UrlContants.Entry, handler);
        ParserRecommendListView.getData(tripUrl, handler);
        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadListener(this);
		return view;
	}
	/**
     * 初始化listview的数据
     */
    private void initListView() {
        final List<ListViewData> listViewData = listData.getData();
        listListViewData.addAll(listViewData);
        if (listListViewData.size() <= 10) {
            listViewAdapter = new RecommendListViewAdapter(getActivity(), listListViewData);
            listView.setAdapter(listViewAdapter);
        } else {
            listViewAdapter.notifyDataSetChanged();
            try {
                refreshLayout.setLoading(false);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String urlq = listViewData.get(position).getView_url().toString();
//                Intent intent = new Intent(getActivity(), DiscountWeb.class);
//                intent.putExtra("url", urlq);
//                startActivity(intent);
            }
        });

    }

    /**
     * 初始化图片list集合
     */
    private void initList() {
        list = new ArrayList<ImageView>();
    }

    /**
     * 初始化控件
     *
     * @param ret
     */
    private void initView(View ret) {
        refreshLayout = (RefreshLayout) ret.findViewById(R.id.main_swipeRefreshLayout);
        listView = (ListView) ret.findViewById(R.id.main_listView);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (visit == 0) {
            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            //每隔两秒钟切换图片
            scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 2, 2, TimeUnit.SECONDS);
        }
        visit++;
    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoad() {
        page++;
        tripUrl = TRIP + page + triplast;
        ParserRecommendListView.getData(tripUrl, handler);
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        page = 1;
        listListViewData.clear();
        tripUrl = TRIP + page + triplast;
        ParserRecommendListView.getData(tripUrl, handler);
    }

    public class ViewPagerTask implements Runnable {

        @Override
        public void run() {
            currentPosition = (currentPosition + 1) % list.size();
            handler1.obtainMessage().sendToTarget();
        }
    }

    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            viewPager.setCurrentItem(currentPosition);
        }
    };

    @Override
    public void onStop() {
        super.onStop();
    }

    public static void parser100(String url, String client_id, String client_secret,
                                 String v, String track_deviceid, String track_app_version, String track_app_channel,
                                 String track_device_info, String track_os, String app_installtime,
                                 final String lat, String lon, String idStr, final Handler handler) {
    	NetWork.getData(url, client_id, client_secret, v, track_deviceid, track_app_version, track_app_channel, track_device_info, track_os, app_installtime, lat, lon, idStr,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        //数据成功 进行解析
                        //进行数据解析
                        FourBean bean = new FourBean();

                        try {

                            JSONObject jsonObject = new JSONObject(responseInfo.result);
                            JSONObject jsonObject1 = jsonObject.getJSONObject("data");

                            bean = JSON.parseObject(jsonObject1.toString(), FourBean.class);
                            Message msg = new Message();
                            msg.what = 2;
                            msg.obj = bean;
                            handler.sendMessage(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(
                            com.lidroid.xutils.exception.HttpException arg0,
                            String arg1) {
                        // TODO Auto-generated method stub

                    }
                });

    }
}
